//
//  HDLoginNewVC.swift
//  HuaDaoPeifu
//
//  Created by ZERO on 2018/6/13.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
    switch (lhs, rhs) {
    case let (l?, r?):
        return l < r
    case (nil, _?):
        return true
    default:
        return false
    }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
    switch (lhs, rhs) {
    case let (l?, r?):
        return l > r
    default:
        return rhs < lhs
    }
}

/*
 登录业务流程：
    * 个人用户登录 -> 成功后退出登录页，发送登录成功通知
    * 团队用户登录 -> 成功后进入选择投保机构页面，选择投保机构，然后发送登陆成功通知
 */
class HDLoginNewVC: UIViewController ,UITextFieldDelegate {

    
    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var passwordView: UIView!
    
    @IBOutlet weak var typeLabel: UILabel!
    
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var passwordTF: UITextField!
    @IBOutlet weak var canSeeBtn: UIButton!
    
    @IBOutlet weak var selectIdBtn: UIButton!
    @IBOutlet weak var loginBtn: UIButton!
    
    var  isCanSeePassWord :Int?
    
    var  userType :HDUserType?

    
    
    var progressAlert = HDProgressAlert()
    //在登录页点击注册跳到哪里：0表示pop到上一页(个人中心需求)，1表示push到注册页(首页登录需求)
//    var registerBtnBackToWhere: Int?
//    var passTiaoZhuan: Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        title = "速赔宝（登录）"
        setUI()

    }

    
    func setUI() {
        phoneView.layer.borderWidth = 1
        phoneView.layer.cornerRadius = 3
        phoneView.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        passwordView.layer.borderWidth = 1
        passwordView.layer.cornerRadius = 3
        passwordView.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        loginBtn.layer.cornerRadius = 3
        selectIdBtn.layer.cornerRadius = 3
        
        isCanSeePassWord = 0;
        if userType == .group {
            self.typeLabel?.text = "团体用户"
            
        }else if userType == .exclusive  {
            self.typeLabel?.text = "专属用户"
            
        }else if userType == .personal  {
            self.typeLabel?.text = "个人用户"
            
        }
        setBarButton()

    }
    
    
    
    func setBarButton() {
        let guideLogin = UserDefaults.standard.bool(forKey: "Guide")
        if guideLogin {
            navigationItem.rightBarButtonItem = nil
            navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(backToGuide))
        }
    }
    func backToGuide() {
        phoneTF.resignFirstResponder()
        passwordTF.resignFirstResponder()
        let backGuide = GuideViewController()
        UIApplication.shared.keyWindow?.rootViewController = backGuide;
        backGuide.scrollView.contentOffset.x = AppConstant.screenWidth*4
        backGuide.scrollView.isScrollEnabled = false
        UserDefaults.standard.set(false, forKey: "Guide")
        self.dismiss(animated: true, completion: nil)
        
    }
    
    @IBAction func canSeeAction(_ sender: UIButton) {
        if isCanSeePassWord == 0 {
            passwordTF.isSecureTextEntry = false
            var str = ""
            str = passwordTF.text!
            passwordTF.text = ""
            passwordTF.text = str

            canSeeBtn.setImage(UIImage(named: "yanjing-2"), for: UIControlState.normal)
            isCanSeePassWord = 1
        }else{
            passwordTF.isSecureTextEntry = true
            canSeeBtn.setImage(UIImage(named: "yanjing-1"), for: UIControlState.normal)
            isCanSeePassWord = 0
        }
        
    }
    
    @IBAction func reSelectAction(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func loginAction(_ sender: UIButton) {
        phoneTF.resignFirstResponder()
        passwordTF.resignFirstResponder()
        
        if phoneTF.text == nil || phoneTF.text == "" {
            SVProgressHUD.showError("手机号不能为空")
            return
        }
        if phoneTF.text?.characters.count != 11 {
            SVProgressHUD.showError("手机号错误")
            return
        }
        if passwordTF.text == nil || passwordTF.text == "" {
            SVProgressHUD.showError("密码不能为空")
            return
        }
        if passwordTF.text?.characters.count < 6 || passwordTF.text?.characters.count > 16 {
            SVProgressHUD.showError("密码错误")
            return
        }
        
        let ptxtStr = passwordTF.text?.cz_md5();
        
        guard let logintype = userType?.rawValue else {
            debugPrint("没有选择用户")
            return
        }
        
        if userType == .personal {
            // 个人用户登录
            let loginParam = PYPLogin(phone: phoneTF.text,ptxt: ptxtStr,did:"", login_type: String(logintype))
            logInForPersonType(loginParam)
        }else if (userType == .group){
            // 团组用户登录
            let loginParam = PYPLogin(phone: phoneTF.text,ptxt: ptxtStr,did:"", login_type: String(logintype))
            logInForGroupType(loginParam)
        }else if (userType == .exclusive){
            // 专属用户登录
        }
    }
    /// 个人用户登录方法
    func logInForPersonType(_ loginParam:PYPLogin)  {
        
        HDApiManagerHandler.requestPersonalLogin_new(loginParam) {[unowned self] (result:HDApiResult?) in
            guard let result = result else{
                SVProgressHUD.showError("网络开小差了哦，请稍后再试...")
                return // 网络请求失败
            }
            
            if (result.status == HDApiResultStatus.Success){
                // 页面跳转，-- 页面状态更新
                guard let data = result.data,
                    let accountInfo = HDAccountInfo.yy_model(withJSON: data) else {
                        SVProgressHUD.showError("网络开小差了哦，请稍后再试...")
                        return
                }
                // 保存用户信息
                accountInfo.phone = loginParam.phone
                HDAccountHandler.saveUserInfo(accountInfo: accountInfo)
                // 页面跳转
                self.loginSuccess()
                
            }else{
                HDIdentityTipsView.initHDIdentityTipsView(showMessage: result.msg!)
            }
        }
    }
    /// 团队用户登录方法
    func  logInForGroupType(_ loginParam:PYPLogin) {
        HDApiManagerHandler.requestPersonalLogin_new(loginParam) { (result:HDApiResult?) in
            guard let result = result else{
                SVProgressHUD.showError("网络开小差了哦，请稍后再试...")
                return // 网络请求失败
            }
            
            if (result.status == HDApiResultStatus.Success){
                // 页面跳转，-- 页面状态更新
                guard let data = result.data,
                    let accountInfo = HDAccountInfo.yy_model(withJSON: data) else {
                        SVProgressHUD.showError("网络开小差了哦，请稍后再试...")
                        return
                }
                // 保存用户信息
                accountInfo.phone = loginParam.phone
                HDAccountHandler.saveUserInfo(accountInfo: accountInfo, NeedsPostNotification: false)
                // 页面跳转
                let agent = HDAgentSelectVC()
                agent.accountInfo = accountInfo
                self.navigationController?.pushViewController(agent, animated: true)
                
            }else{
                HDIdentityTipsView.initHDIdentityTipsView(showMessage: result.msg!)
            }
        }
        
       
    }
    /// 个人用户登陆成功
    func loginSuccess() {
        let a = UserDefaults.standard.bool(forKey: "Guide")
        if a {
            let vc = ViewController();
            UIApplication.shared.keyWindow?.rootViewController = vc;
            self.dismiss(animated: true, completion: nil)
            UserDefaults.standard.set(false, forKey: "Guide")
        }else{
            self.navigationController?.popToRootViewController(animated: true)
        }
    }
    
    /**
     *注册账号
     */
    @IBAction func registAction(_ sender: UIButton) {
        let register = HDRegistVC()
        register.accountType = userType

//        register.logBtnBackToWhere = passTiaoZhuan
//        register.passType = 1
//        if registerBtnBackToWhere == 1 {
//            navigationController?.popViewController(animated: true)
//        }else {
            navigationController?.pushViewController(register, animated: true)
//        }
    }
    /**
     *找回密码
     */
    @IBAction func forgetPwAction(_ sender: Any) {
       
        let findPW = HDFindPWVC()
        findPW.accountType = userType
        
        //        register.logBtnBackToWhere = passTiaoZhuan
        //        register.passType = 1
        //        if registerBtnBackToWhere == 1 {
        //            navigationController?.popViewController(animated: true)
        //        }else {
        navigationController?.pushViewController(findPW, animated: true)

    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
